package com.budwk.app.sqfw.services.customservice.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.component.CommunityStreetComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.dto.SqfwCompleteFlowUpdateDTO;
import com.budwk.app.sqfw.models.Sqfw_cenSusPaper;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.services.common.SqfwCustomForAdminCommonService;
import com.budwk.app.sqfw.vo.CheckDataForAdminVO;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfw.vo.GenerateWordAndPdfUrlVO;
import com.budwk.app.sqfw.vo.SqfwCustomForAdminCommonVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowExcelParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowPdfParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelGenerator;
import com.budwk.app.sqfwDoc.dto.CompleteFlowTemplateCodeUpdateDTO;
import com.budwk.app.sqfwV2.dto.dayingRoad.DaYingLuRedRecordPdfDTO;
import com.budwk.app.sqfwV2.dto.dayingRoad.DaYingLuWhiteRecordPdfDTO;
import com.budwk.app.sqfwV2.enums.*;
import com.budwk.app.sqfwV2.generator.dayingRoadPdf.RedHandleCateringRecordsPdfGenerator;
import com.budwk.app.sqfwV2.generator.dayingRoadPdf.WhiteHandleCateringRecordsPdfGenerator;
import com.budwk.app.sqfwV2.service.dulaying.PropagandaOrScreeningExcelService;
import com.budwk.app.sqfwV2.service.dulaying.PropagandaOrScreeningPdfService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysLogService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.adminUtils.CommonCheckUtils;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.security.utils.SecurityUtil;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.annotation.Table;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.dao.util.cri.Static;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.apache.commons.lang3.ObjectUtils;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import static com.budwk.app.util.poiUtils.CommonFormOfficeUtils.generateWordDocument;

/**
 * @program: dfxy-community
 * @description: 都拉营宣传排查服务实现
 * @author: LJT
 * @create: 2024-03-07 16:11
 **/
@IocBean(name = "DuLaYingProChkForAdminService")
@Slf4j
public class DuLaYingProChkForAdminServiceImpl extends PropagandaOrScreeningExcelService implements SqfwCustomForAdminCommonService {

    @Inject
    SysUserService sysUserService1;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    @Inject
    private PropagandaOrScreeningPdfService propagandaOrScreeningPdfService;

    @Inject
    private SysLogService sysLogService;

    @Override
    public Pagination list(SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        long startTime = System.currentTimeMillis();
        // 构造查询条件
        Criteria criteria = buildQueryCond(bean);
        log.info("DuLaYingProChkForAdminServiceImpl-list-SQL: {}", criteria.toString());
        Pagination pagination = sqfwFormsummaryNewService.listPage(bean.getPageNo(), bean.getPageSize(), criteria);
        List<Sqfw_formSummary_new> sqfwCustomForAdminCommonVOList = pagination.getList(Sqfw_formSummary_new.class);
        if (ObjectUtil.isNotEmpty(sqfwCustomForAdminCommonVOList)) {
            List<SqfwCustomForAdminCommonVO> finalCommonVOList = new ArrayList<SqfwCustomForAdminCommonVO>();
            Map<String, String> pdfUrlMap = CommonCheckUtils.getPdfUrlByFlowId(sqfwCustomForAdminCommonVOList);
            sqfwCustomForAdminCommonVOList.forEach(source -> {
                SqfwCustomForAdminCommonVO target = new SqfwCustomForAdminCommonVO();
                BeanUtil.copyProperties(source, target);
                target.setPdfUrl(pdfUrlMap.get(target.getSqfwFlowId()));
                finalCommonVOList.add(target);
            });
            pagination.setList(finalCommonVOList);
        }
        log.info("DuLaYingProChkForAdminServiceImpl-list-耗时: {}ms", System.currentTimeMillis() - startTime);
        return pagination;
    }

    @Override
    @Aop(TransAop.READ_COMMITTED)
    public int delete(String id) {
        int num = 0;
        Sqfw_formSummary_new sqfwFormsummaryNew = sqfwFormsummaryNewService.fetch(id);
        if (sqfwFormsummaryNew == null) {
            return num;
        }
        log.info("删除记录:{},{}", SecurityUtil.getUserId(), id);
        sqfwCompleteflowService.deleteAndUpdateWO(sqfwFormsummaryNew.getSqfwFlowId());
        return num;
    }

    @Override
    public int batchDelete(List<String> ids) {
        if (ids == null || ids.size() == 0) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        // 查询数据
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary::getId, "in", ids);
        List<Sqfw_formSummary_new> newList = sqfwFormsummaryNewService.query(cnd);
        if (newList.isEmpty()) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        String userId = SecurityUtil.getUserId();
        // 异步执行删除操作
        if (!newList.isEmpty()) {
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            CompletableFuture.runAsync(() -> {
                for (Sqfw_formSummary_new sqfwFormSummaryNew : newList) {
                    batchDeleteDataNew(userId, sqfwFormSummaryNew);
                }
            }, executorService);
            executorService.shutdown();
        }
        return newList.size();
    }

    @Override
    @Aop(TransAop.READ_COMMITTED)
    public int update(Sqfw_formSummary_new sqfwFormsummaryNew) {
        sqfwFormsummaryNew.setUpdateBy(SecurityUtil.getUserId());
        sqfwFormsummaryNew.setUpdateDate(new Date());
        return sqfwFormsummaryNewService.updateIgnoreNull(sqfwFormsummaryNew);
    }

    @Override
    public List<GenerateExcelUrlVO> downloadExcel(List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        List<GenerateExcelUrlVO> generateExcelUrlVOList = new ArrayList<GenerateExcelUrlVO>();
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
        // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾选id下载
        if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
            Criteria criteria = buildQueryCond(bean);
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(criteria);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(sqfwFormsummaryNewService.query(criteria).stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new ArrayList<GenerateExcelUrlVO>();
            }
        } else {
            Cnd cnd = Cnd.NEW();
            cnd.and(Sqfw_formSummary_new::getId, "IN", bean.getFormSummaryNewIdList());
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(cnd);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new ArrayList<GenerateExcelUrlVO>();
            }
        }

        // 2.0版本
        CompleteFlowExcelParamForController paramForController = new CompleteFlowExcelParamForController();
        paramForController.setFormSummaryIdList(bean.getFormSummaryNewIdList());
        paramForController.setExcelCreateConfigList(excelConfigList);
        paramForController.setUserId(SecurityUtil.getUserId());
        List<ResultOfExcelGenerator> excel = super.createExcelForAdmin(paramForController);
        if (CollectionUtil.isNotEmpty(excel)) {
            generateExcelUrlVO.setExcelUrl(excel.get(0).getExcelUrl());
            generateExcelUrlVOList.add(generateExcelUrlVO);
        }
        return generateExcelUrlVOList;
    }

    @Override
    public GenerateWordAndPdfUrlVO downloadPdf(List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        return null;
    }

    @Override
    public List<GenerateExcelUrlVO> downloadPdfList(List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾选id下载
        if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
            Criteria criteria = buildQueryCond(bean);
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(criteria);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new ArrayList<GenerateExcelUrlVO>();
            }
        } else {
            Cnd cnd = Cnd.NEW();
            cnd.and(Sqfw_formSummary_new::getId, "IN", bean.getFormSummaryNewIdList());
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(cnd);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new ArrayList<GenerateExcelUrlVO>();
            }
        }
        return propagandaOrScreeningPdfService.downPdfListToSummaryIds(excelConfigList, bean.getFormSummaryNewIdList());
    }

    @Override
    public Criteria buildQueryCond(SqfwCustomForAdminCommonVO bean) {
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();

        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        // 组装查询条件
        if (StringUtils.isNotBlank(bean.getPageOrderName()) && Strings.isNotBlank(bean.getPageOrderBy())) {
            if (bean.getPageOrderBy().equals(CommonConstants.ASC)) {
                cri.getOrderBy().asc(bean.getPageOrderName());
            }
            if (bean.getPageOrderBy().equals(CommonConstants.DESC)) {
                cri.getOrderBy().desc(bean.getPageOrderName());
            }
        } else {
            cri.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        }
        // 类型
        criSql.andEquals(SqfwCustomForAdminCommonVO::getType, bean.getType());

        Sys_user sysUser = sysUserService1.fetch(SecurityUtil.getUserId());
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new AppException(ResultCode.USER_NOT_FOUND.getMsg());
        }
        // 区域5级检查
        CommonCheckUtils.checkAreaRange(criSql);
        // 省
        if (StringUtils.isNotBlank(bean.getProvince()) && !CommonCheckUtils.ZHISHU.equals(bean.getProvince())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getProvince, bean.getProvince());
        }
        // 市
        if (StringUtils.isNotBlank(bean.getCity()) && !CommonCheckUtils.ZHISHU.equals(bean.getCity())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getCity, bean.getCity());
        }
        // 区
        if (StringUtils.isNotBlank(bean.getDistrict()) && !CommonCheckUtils.ZHISHU.equals(bean.getDistrict())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getDistrict, bean.getDistrict());
        }
        // 街道
        if (StringUtils.isNotBlank(bean.getCounty()) && !CommonCheckUtils.ZHISHU.equals(bean.getCounty())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getCounty, bean.getCounty());
        }
        // 时间
        if (ObjectUtil.isNotEmpty(bean.getQueryStartTime()) && ObjectUtil.isNotEmpty(bean.getQueryEndTime())) {
            criSql.andBetween(Sqfw_formSummary_new::getFillDate,
                    CommunityStreetComponent.handleStartQueryTime(bean.getQueryStartTime()),
                    CommunityStreetComponent.handleEndQueryTime(bean.getQueryEndTime()));
        }
        // 辖区
        if (StringUtils.isNotBlank(bean.getCommunity()) && !CommonCheckUtils.ZHISHU.equals(bean.getCommunity())) {
            criSql.andEquals(Sqfw_formSummary_new::getCommunity, bean.getCommunity());
        }
        // 全局搜索
        if (StringUtils.isNotEmpty(bean.getQueryAll())) {
            SqlExpressionGroup address = Cnd.exps(new Static("param_data->>'address' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup type = Cnd.exps(new Static("param_data->>'type' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup theme = Cnd.exps(new Static("param_data->>'theme' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup county = Cnd.exps(new Static("county like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup community = Cnd.exps(new Static("community like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup createUserName = Cnd.exps(new Static("create_user_name like '%" + bean.getQueryAll() + "%'"));
            criSql.and(address.or(type).or(theme).or(county).or(community).or(createUserName));
        }
        // 需要排除的数据
        criSql.andNotEquals(Sqfw_formSummary_new::getFillDate, CommonConstants.WASTE_CREATE_TIME);
        // 地点
        if (StringUtils.isNotBlank(bean.getAddress())) {
            criSql.andEquals("param_data->>'address'", bean.getAddress());
        }
        // 记录类型
        if (StringUtils.isNotBlank(bean.getCheckType())) {
            criSql.andEquals("param_data->>'type'", bean.getCheckType());
        }
        // 主题
        if (ObjectUtil.isNotEmpty(bean.getTheme())) {
            criSql.andLike("param_data->>'theme'", bean.getTheme());
        }
        // 是否存在隐患
        if (ObjectUtil.isNotEmpty(bean.getWhetherThereIsAnyHiddenDanger())) {
            if ("false".equals(bean.getWhetherThereIsAnyHiddenDanger())) {
                SqlExpressionGroup whetherThereIsAnyHiddenDanger = Cnd.exps(new Static("param_data->>'whetherThereIsAnyHiddenDanger' = '" + bean.getWhetherThereIsAnyHiddenDanger() + "'"));
                SqlExpressionGroup checkType = Cnd.exps(new Static("param_data->>'type' = '" + PropagandaOrScreeningEnum.PROPAGANDA.getName() + "'"));
                criSql.and(whetherThereIsAnyHiddenDanger.or(checkType));
            } else {
                criSql.andEquals("param_data->>'whetherThereIsAnyHiddenDanger'", bean.getWhetherThereIsAnyHiddenDanger());
            }
        }
        // 检查人员
        if (ObjectUtil.isNotEmpty(bean.getCreateUserName())) {
            criSql.andEquals(Sqfw_formSummary_new::getCreateUserName, bean.getCreateUserName());
        }
        return cri;
    }

    @Override
    public List<CheckDataForAdminVO> checkDataInfoList(SqfwCustomForAdminCommonVO bean) {
        // 检查数据
        int a = sqfwFormsummaryNewService.count(Cnd.where(Sqfw_formSummary_new::getId, "IN", bean.getFormSummaryNewIdList())
                .and("param_data->>'type'", "=", PropagandaOrScreeningEnum.PROPAGANDA.getName()));
        int b = sqfwFormsummaryNewService.count(Cnd.where(Sqfw_formSummary_new::getId, "IN", bean.getFormSummaryNewIdList())
                .and("param_data->>'type'", "=", PropagandaOrScreeningEnum.SCREENING.getName()));

        List<CheckDataForAdminVO> checkDataForAdminVOList = new ArrayList<CheckDataForAdminVO>();
        for (PropagandaOrScreeningEnum item : PropagandaOrScreeningEnum.values()) {
            CheckDataForAdminVO checkDataForAdminVO = new CheckDataForAdminVO();
            checkDataForAdminVO.setFileIdentity(String.valueOf(item.getCode()));
            checkDataForAdminVO.setCreateConditionFlag(false);
            checkDataForAdminVO.setFileName(item.getCompilationName());
            if ("1".equals(item.getCode()) || "2".equals(item.getCode())) {
                checkDataForAdminVO.setFileName(checkDataForAdminVO.getFileName() + ".pdf");
            }
            if ("1".equals(item.getCode()) && a > 0) {
                checkDataForAdminVO.setCreateConditionFlag(true);
            } else if ("2".equals(item.getCode()) && b > 0) {
                checkDataForAdminVO.setCreateConditionFlag(true);
            } if ("3".equals(item.getCode())) {
                checkDataForAdminVO.setCreateConditionFlag(true);
                checkDataForAdminVO.setFileName(checkDataForAdminVO.getFileName() + ".xlsx");
            }
            checkDataForAdminVOList.add(checkDataForAdminVO);
        }
        return checkDataForAdminVOList;
    }

    @Override
    public void reGeneratePdf(String id) {
        CompleteFlowPdfParamForController paramForController = new CompleteFlowPdfParamForController();
        CompleteFlowTemplateCodeUpdateDTO dto = new CompleteFlowTemplateCodeUpdateDTO();
        Sqfw_formSummary_new sqfwFormSummaryNew = sqfwFormsummaryNewService.fetch(id);
        Sqfw_completeflow sqfwCompleteflow = sqfwCompleteflowService.fetch(sqfwFormSummaryNew.getSqfwFlowId());
        SqfwCompleteFlowUpdateDTO sqfwCompleteFlowUpdateDTO = new SqfwCompleteFlowUpdateDTO();
        BeanUtil.copyProperties(sqfwCompleteflow, sqfwCompleteFlowUpdateDTO);
        dto.setCompleteFlow(sqfwCompleteFlowUpdateDTO);
        dto.setFormSummary(sqfwFormSummaryNew);
        paramForController.setCompleteFlowId(sqfwCompleteFlowUpdateDTO.getId());
        paramForController.setCompleteFlowDataDTO(dto);
        paramForController.setUserId(SecurityUtil.getUserId());
        propagandaOrScreeningPdfService.reCreatePdfAndMsg(paramForController);
    }

    /**
     * 下载模板
     *
     * @param config
     * @return
     */
    private String downWordTemplate(ExcelCreateConfig config) {
        String fileName = "";
        String templateName = "";

        Map<String, Object> dataMap = JSONUtil.parseObj(new Sqfw_formSummary_new(), false);
        if (RedWhitePdf.WHITE_INFORMATION_STATISTICS.getCode().equals(config.getFileIdentity())) {
            fileName = RedWhitePdf.WHITE_INFORMATION_STATISTICS.getName();
            templateName = new WhiteHandleCateringRecordsPdfGenerator().getTemplateName();
            dataMap.putAll(JSONUtil.parseObj(new DaYingLuWhiteRecordPdfDTO(), false));
        }
        if (RedWhitePdf.RED_TRACKING_REPORT.getCode().equals(config.getFileIdentity())) {
            fileName = RedWhitePdf.RED_TRACKING_REPORT.getName();
            templateName = new RedHandleCateringRecordsPdfGenerator().getTemplateName();
            dataMap.putAll(JSONUtil.parseObj(new DaYingLuRedRecordPdfDTO(), false));
        }

        for (String key : dataMap.keySet()) {
            dataMap.put(key, "");
        }

        dataMap.put("yyyy", "");
        dataMap.put("mm", "");
        dataMap.put("dd", "");
        dataMap.put("hh", "");
        dataMap.put("checkedUnitLeaders", new ArrayList<>());
        dataMap.put("fillDateStr", "");

        XWPFTemplate xwpfTemplate = generateWordDocument(dataMap, null, templateName);
        NiceXWPFDocument xwpfDocument = xwpfTemplate.getXWPFDocument();
        GenerateWordAndPdfUrlVO vo = CommonFormOfficeUtils.wordUpload(Arrays.asList(xwpfDocument), fileName.replace("合集", "模板"));
        return vo.getWordUrl();
    }

    /**
     * 批量删除
     *
     * @param userId
     * @param data
     */
    private void batchDeleteDataNew(String userId, Sqfw_formSummary_new data) {
        //1 记录日志
        sysLogService.insertDelLog(userId, JSONObject.toJSONString(data), Sqfw_cenSusPaper.class.getAnnotation(Table.class).value(),
                "com.budwk.app.sqfw.services.customservice.DaYingLuSecurityForAdminServiceImpl.batchDeleteDataNew",
                "com.budwk.app.sqfw.controllers.admin.DaYingLuSecurityForAdminController.batchDelete");
        // 2 删除数据
        sqfwCompleteflowService.deleteAndUpdateWO(data.getSqfwFlowId());
    }
}
